package distributed.lock.expand;

import static distributed.lock.factory.RedisFactory.getJedis;
import static distributed.lock.factory.RedisFactory.recycleJedis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import distributed.lock.util.IpUtil;

/**
 * @comment 基于redis的分布式锁
 * @date 2015年11月9日 上午11:27:10
 * @author zhouxiao
 * @qq 772716714
 * @version 1.0
 */
public class RedisLock implements Lock {

	private static Logger logger = LoggerFactory.getLogger(RedisLock.class);
	private static final int DEFAULT_EXPIRE_TIME = 120;
	private static final String IP = IpUtil.getIp();

	public void lock(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			while (true) {
				logger.warn("lock key: " + key);
				long lock = jedis.setnx(key, value);
				if (lock == 1) {
					jedis.expire(key, DEFAULT_EXPIRE_TIME);
					logger.warn("set lock success, key: " + key + " on ip " + IP);
					break;
				} else {
					logger.warn("set lock faile : " + key + " locked by another business on ip " + IP);
					Thread.sleep(100);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			recycleJedis(jedis);
		}
	}

	public void unLock(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			jedis.del(key);
			logger.warn("delete lock  : " + key + " on ip " + IP);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			recycleJedis(jedis);
		}
	}

}
